<?php
namespace app\home\controller;
use \think\Cookie;
use think\Db;
use \think\View;
use \think\Model;
use \think\Request;
use \GatewayClient\Gateway;
class User extends Model
{
    protected $resultSetType = 'collection';
}

class StatusData extends Model
{
    protected $resultSetType = 'collection';
    protected $createTime = 'time';
    protected $updateTime = false;
}

class ChatData extends Model
{
    protected $resultSetType = 'collection';
    protected $createTime = 'time';
    protected $updateTime = false;
}
class Chat extends \think\Controller
{
    public function chat()     //在线聊天
    {
        global $ip_address;
        require_once 'application/ip.php';
        $cookie = Cookie::get('safecode');
        $person_data = User::getBySafecode($cookie);
        $chat_data = ChatData::order('time', 'asc')->select()->toArray();
        $time1 = ChatData::order('time', 'desc')->limit(1)->select()->toArray();

        if (!$time1) {
            $time['time'] = '无';
        } else {
            $time = $time1[0];
        }
        $view = new View();
        $view->assign('ip', $ip_address);
        $view->assign('time', $time);
        $view->assign('chat', $chat_data);
        $view->assign('user', $person_data);
        return $view->fetch('chat', [], ['__PUBLIC__' => '/public/static']);
    }
    public function bind()     //绑定用户id与聊天id
    {
        global $ip_address;
        require_once 'application/ip.php';
        $ip = $ip_address . ':1238';
        Gateway::$registerAddress = $ip;

        $cookie = Cookie::get('safecode');
        $person_data = User::getBySafecode($cookie);
        $uid = $person_data['Id'];
        $client_id = input('post.client_id');
        Gateway::bindUid($client_id, $uid);
        $message = [
            'type' => 'login_in',
        ];
        Gateway::sendToAll(json_encode($message));
    }
    public function in_data()   //聊天信息录入
    {
        $chat_data = input('post.');
        $chat = new ChatData($chat_data);
        print_r($chat_data);
        if ($chat->save()) {
            $callback['result'] = 'success';
            return json($callback);
        } else {
            $callback['result'] = 'error';
            return json($callback);
        }
    }
    public function online()   //在线用户列表
    {
        global $ip_address;
        require_once 'application/ip.php';
        $ip = $ip_address . ':1238';
        Gateway::$registerAddress = $ip;
        $online_id = Gateway::getAllUidList();
        $array = array();
        foreach ($online_id as $uid) {
            $user_list = User::getbyId($uid)->toArray();
            array_push($array, $user_list);
        }
        return json($array);
    }
}